package com.newgoldcurrency.activities.main;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.anythink.banner.api.ATBannerListener;
import com.anythink.banner.api.ATBannerView;
import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.AdError;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.adapter.IncomeAdapter;
import com.newgoldcurrency.bean.IncomeBean;
import com.newgoldcurrency.databinding.FragmentIncomeBinding;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class IncomeFragment extends Fragment {
    private static final String TAG = "emmmmmmmmm";
    private FragmentIncomeBinding binding;
    private int index=0;
    private final List<IncomeBean> data=new ArrayList<>();
    private IncomeAdapter adp;
    private final List<Call>calls=new ArrayList<>();
    private MainActivity activity;
    private int current=1;
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity=(MainActivity)getActivity();
        binding = FragmentIncomeBinding.inflate(inflater, container, false);
        binding.incomeTab.addTab(binding.incomeTab.newTab().setText(getString(R.string.i_made_it)));
        binding.incomeTab.addTab(binding.incomeTab.newTab().setText(getString(R.string.made_by_miners)));
        binding.incomeTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                index=tab.getPosition();
                current=1;
                refresh(true,null);
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) { }
            @Override
            public void onTabReselected(TabLayout.Tab tab) { }
        });
        binding.incomeRefresh.setRefreshHeader(new ClassicsHeader(activity));
        binding.incomeRefresh.setRefreshFooter(new ClassicsFooter(activity));
        adp=new IncomeAdapter(activity,data);
        binding.incomeLv.setAdapter(adp);
        binding.incomeRefresh.setOnRefreshListener(refreshLayout -> refresh(true,refreshLayout));
        binding.incomeRefresh.setOnLoadMoreListener(refreshLayout -> refresh(false,refreshLayout));
        initBanner();
        refresh(true,null);
        return binding.getRoot();
    }
    private void initBanner() {
        ATBannerView mBannerView = new ATBannerView(activity);
        mBannerView.setPlacementId("b620dbae9744a9");
        int width = Tools.screenWidthPixels(activity);
        int height =  ViewGroup.LayoutParams.WRAP_CONTENT;
        mBannerView.setLayoutParams(new FrameLayout.LayoutParams(width, height));
        mBannerView.setBannerAdListener(new ATBannerListener() {
            @Override
            public void onBannerLoaded() {
                Log.i(TAG, "onBannerLoaded: ");
                if (binding!=null)binding.incomeBanner.setVisibility(View.VISIBLE);
            }
            @Override
            public void onBannerFailed(AdError adError) {
                Log.i(TAG, "onBannerFailed: "+adError);
            }
            @Override
            public void onBannerClicked(ATAdInfo atAdInfo) {
            }
            @Override
            public void onBannerShow(ATAdInfo atAdInfo) {
            }
            @Override
            public void onBannerClose(ATAdInfo atAdInfo) {
                if (binding!=null)binding.incomeBanner.setVisibility(View.GONE);
            }
            @Override
            public void onBannerAutoRefreshed(ATAdInfo atAdInfo) {
            }
            @Override
            public void onBannerAutoRefreshFail(AdError adError) {
            }
        });
        binding.incomeBanner.addView(mBannerView);
        if (App.ShowBean.hasBanner){
            mBannerView.loadAd();
        }else {
            binding.incomeBanner.setVisibility(View.GONE);
        }
    }
    private void refresh(boolean isRefresh,RefreshLayout layout) {
        for (Call c :calls) c.cancel();
        if (isRefresh){
            data.clear();
            current=1;
        }else {
            current++;
        }
        HashMap<String, String> map=new HashMap<>();
        String url;
        map.put("token", App.sp.getString("token",""));
        map.put("pageNumber", String.valueOf(current));
        map.put("pageSize", "5");
        if (index==0){
            url="miner/getMyIncome";
        }else {
            url="miner/getMinerIncome";
        }
        Network.post(map, url, call -> {
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    activity.runOnUiThread(() -> {
                        try {
                            String str= Objects.requireNonNull(response.body()).string();
                            if (Tools.isJson(str)){
                                JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
                                if (jo.get("message").getAsString().equals("Get mine record success")){
                                    JsonObject res = jo.get("data").getAsJsonObject();
                                    binding.incomeTotalBalance.setText(getString(R.string.total_balance,res.get("totalBalance").getAsString()));
                                    binding.incomeHaveInvited.setText(getString(R.string.have_invited,res.get("minersCount").getAsString()));
                                    if (index==0){
                                        binding.incomeTotalGoldCoin.setText(getString(R.string.myGoldCoins,res.get("myGoldCoins").getAsString()));
                                        data.addAll(new Gson().fromJson(res.get("myRecords"),new TypeToken<List<IncomeBean>>(){}.getType()));
                                    }else{
                                        binding.incomeTotalGoldCoin.setText(getString(R.string.minerGoldCoins,res.get("minerGoldCoins").getAsString()));
                                        data.addAll(new Gson().fromJson(res.get("minerRecords"),new TypeToken<List<IncomeBean>>(){}.getType()));
                                    }
                                    adp.notifyDataSetChanged();
                                    if (layout!=null){
                                        if (isRefresh){
                                            binding.incomeRefresh.finishRefresh();
                                        }else {
                                            layout.finishLoadMore();
                                        }
                                    }
                                }else{
                                    Tools.toast(jo.get("message").getAsString());
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
                }
            });
            calls.add(call);
        });
        adp.notifyDataSetChanged();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        for (Call c :calls) c.cancel();
        binding=null;
    }
}